import { defineStore } from "pinia";
import { cloneDeep, isEmpty } from "lodash-es";
import menuJson from "./data";

const initiateStore = {
  title: "管理平台",
  collapsed: false, // 左侧展开收起
  menuList: menuJson.data.sort((a,b) => {
    return b.funcSort - a.funcSort;
  })?.map(it => {
    if (it.children?.length) {
      it.children = it.children.sort((a,b) => b.funcSort - a.funcSort);
    }
    return it;
  }), // 菜单列表
  headTabNavList: [], // 头部tab导航列表
  tabSelect: "",
  openKeys: ["/test"], //默认选择 菜单
  pagesMap: {}, //页面Map router对象
};
const useMenuStore = defineStore("menu", () => {
  const menuState = reactive({ ...cloneDeep(initiateStore) });

  // 初始化菜单配置
  const initMenuList = async () => {
    try {
      const res = menuJson;
      if (res.success && res.data?.length) {
        const menuList = sortMenuList(res.data);
        // 只有子应用才做操作。
        localStorage.setItem("MENU_LIST", menuList);
        const [pagesMap] = handleRouterToPageMap(menuList);
        menuState.pagesMap = pagesMap;
        if (menuState.tabSelect && !isEmpty(pagesMap)) {
          menuState.headTabNavList = [
            ...menuState.headTabNavList,
            pagesMap[menuState.tabSelect],
          ];
        }
        menuState.menuList = menuList;
        return menuList;
      }
      return Promise.reject();
    } catch (error) {
      return Promise.reject(error);
    }
  };

  const getMenuList = () => {
    let menuList = [];
    if (menuState.menuList?.length) {
      menuList = menuState.menuList;
    }
    if (!menuList.length) {
      menuList = localStorage.getItem("MENU_LIST");
    }
    menuList = getCurrentMenuList(menuList);
    menuList = sortMenuList(menuList) || [];
    const [pagesMap] = handleRouterToPageMap(menuList) || [];
    menuState.pagesMap = pagesMap;
    if (menuState.tabSelect && !isEmpty(pagesMap)) {
      menuState.headTabNavList = [
        ...menuState.headTabNavList,
        pagesMap[menuState.tabSelect],
      ];
    }
    menuState.menuList = menuList;
    return menuList;
  };

  const reset = () => {
    Object.assign(menuState, cloneDeep(initiateStore));
    localStorage.removeItem("MENU_LIST");
  };

  return { menuState, getMenuList, initMenuList, reset };
},
{
    persist: {
      debug: import.meta.env.DEV,
      pick: ['menuState'],
    },
}
);

export { useMenuStore };

function getCurrentMenuList(list) {
  if (isEmpty(list)) {
    return [];
  }
  if (!window.__POWERED_BY_WUJIE__) {
    return list;
  }
  let result = list;
  list.forEach((it) => {
    const { children } = it || {};
    children.map((v) => {
        // 子应用名字
      if (v.appName === "APP") {
        result = [v];
      }
    });
  });
  return result;
}

/**
 * @param {排序菜单} menuList
 * @returns
 */
export function sortMenuList(menuList) {
  if (!menuList?.length) {
    return menuList || [];
  }

  menuList = menuList.sort((a, b) => b.funcSort - a.funcSort);
  const loop = (arr = []) => {
    arr = arr.sort((a, b) => b.funcSort - a.funcSort);
    arr.forEach((it) => {
      const { children = [] } = it || {};
      if (children?.length) {
        it.children = loop(children);
      }
    });
    return arr;
  };
  menuList.forEach((it) => {
    const { children = [] } = it || {};
    if (children?.length) {
      it.children = loop(children);
    }
  });

  return menuList;
}

export function handleRouterToPageMap(routerList) {
  let routerMap = {};
  let mList = [];
  function handleMap(list, parentItem) {
    if (list && list.length) {
      for (let item of list) {
        if (!parentItem) {
          // 基座的是name
          item.breadCrumb = [item.funcName || item.name];
          item.menuKeys = [item.path];
        } else {
          const parBreadCrumb = [...parentItem.breadCrumb];
          const parMenuKeys = [...parentItem.menuKeys];
          item.breadCrumb = [...parBreadCrumb, item.funcName || item.name];
          item.menuKeys = [...parMenuKeys, item.path];
        }

        if (item.children.length) {
          routerMap[item.path] = {
            ...item,
          };
          mList.push(routerMap[item.path]);
          handleMap(item.children, item);
        } else {
          routerMap[item.path] = {
            ...item,
          };
          mList.push(routerMap[item.path]);
        }
      }
    } else {
      return;
    }
  }
  handleMap(routerList);
  return [routerMap, mList];
}

/**
 *
 * @param {*} route
 * status: 表示是否带参数
 * originalPath 不带参数，纯后端路由
 * totalPath：携参数
 * @returns
 */
export function routerIsParamsOrQuery(route) {
  const { params, query } = route;
  // 路径包含参数
  if (Object.keys(params).length || Object.keys(query).length) {
    let path = route.path;
    let originalPath = route.path;
    if (Object.keys(params).length) {
      const paramsLenght = Object.keys(params).length;
      const pathList = path.split("/").filter((v) => v !== "");
      pathList.splice(pathList.length - paramsLenght);
      let orPath = "";
      pathList.forEach((item) => {
        orPath += "/" + item;
      });
      if (orPath) {
        originalPath = orPath;
      }
    }
    const queryKeys = [];
    for (let key of Object.keys(query)) {
      if (!query[key]) {
        continue;
      }
      if (!queryKeys.length) {
        path += `?${key}=${query[key]}`;
        queryKeys.push(key);
      } else {
        path += `&${key}=${query[key]}`;
      }
    }
    return { status: true, originalPath: originalPath, totalPath: path };
  }
  return { status: false, originalPath: route.path, totalPath: route.path };
}

/**
 * 获取菜单列表中重定向第一个路由
 * @param {*} routerList
 * path 路径，查看传过来的路径是否在里面。
 * @returns
 */
export function getDefaultPage(routerList, path = getRouterPath()) {
  if (!routerList?.length) {
    return "";
  }
  let defaultPage = "";
  function handleList(list) {
    list.some((it) => {
      const { funcType, isShow, children = [] } = it || {};
      // 1级路由继续遍历，安全管理不支持一级路由就点击
      if (funcType === "DIR" && isShow) {
        return handleList(children);
      }
      // 1级路由是文件夹|2or3级路由是文件并且是显示的
      if (funcType === "TAB" && isShow) {
        const isMatch = path === it.path;
        // 判断二级路由没有3级路由
        if (!children?.length) {
          // 没有定向页面或者匹配了
          if (!path || isMatch) {
            defaultPage = it.path;
            return true;
          }
          // 继续遍历
          return false;
        }
        // 判断是否有3级路由，如果3级路由有funcType= TAB && show
        const childrenType = children.some(
          (it) => it.funcType === "TAB" && it.isShow
        );
        if (childrenType) {
          return handleList(children);
        }

        // 没有定向页面或者匹配了
        if (!path || isMatch) {
          defaultPage = it.path;
          return true;
        }

        // 继续遍历
        return false;
      }
      return false;
    });

    return defaultPage;
  }

  handleList(routerList);
  return defaultPage;
}

export function getRouterPath() {
  const originHref = window.__POWERED_BY_WUJIE__
    ? window.parent.location.href
    : window.location.href;
  const href = decodeURIComponent(originHref);
  const [, childEnterPath, allPath] = href.split("#");
  const isChildProject = window.__POWERED_BY_WUJIE__;
  // 基座的子应用
  if (isChildProject) {
    const [path = ""] = allPath?.split("?") || [];
    // 截取的问题
    if (path === "/") {
      return "";
    }
    return path;
  }

  // 单独应用
  const [path = ""] = childEnterPath?.split("?") || [];
  // 截取的问题
  if (path === "/") {
    return "";
  }
  return path;
}
